
<template>
  <div class="">
    <el-row v-for="(item,index) in ['大区:','城市:','门店:']" :key="item">
      <el-col :span="2">{{ item }}</el-col>
      <el-col :span="20">
        <el-tag
          v-for="tag in bigData[keyMatch[index]]"
          :key="tag.value"
          closable
          :title="tag.name"
          @close="handleClose(tag.value,index)"
        >
          {{ tag.name.length>8?`${tag.name.substr(0,8)}...`:tag.name }}
        </el-tag>
      </el-col>
      <el-col style="float:right" :span="2">
        <el-link :underline="false" type="primary" @click="addTag(index)">添加</el-link>
      </el-col>
    </el-row>
    <com-dialog :title="title" :visible.sync="visible">
      <el-input
        v-model="searchVal"
        clearable
        placeholder="请输入搜索"
        prefix-icon="el-icon-search"
        @change="search"
      />
      <div class="content">
        <div class="select-content">
          <el-tag
            v-for="tag in selectData"
            :key="tag.value"
            closable
            @close="clearTag(tag.value)"
          >
            {{ tag.name.length>8?`${tag.name.substr(0,8)}...`:tag.name }}
          </el-tag>
        </div>
        <div class="divier" />
        <div class="select-cont">
          <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
            <el-checkbox v-for="item in listData" :key="item.value" :label="item.value">{{ item.name }}</el-checkbox>
          </el-checkbox-group>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="reset">重 置</el-button>
        <el-button size="small" type="primary" @click="sure">确 定</el-button>
      </span>
    </com-dialog>
  </div>
</template>

<script>
import { mapActions, mapState } from 'vuex';
import { isNS } from '@/utils/tools';
import ComDialog from './dialog';
const KEY_MATCH_ARRAY = ['regionList', 'cityList', 'storeList'];
export default {
  components: {
    ComDialog
  },
  props: {
    boxs: {
      type: Object,
      default: () => ({})
    },
    bigData: {
      type: Object,
      default: () => ({
        regionList: [],
        cityList: [],
        storeList: []
      })
    }
  },
  data () {
    return {
      listData: [], //
      checkedCities: [], // 选中项
      selectData: [], // 选中TAG
      searchVal: '', // 搜索值
      title: '添加大区',
      visible: false,
      keyMatch: KEY_MATCH_ARRAY,
      cacheSelectCitys: [], // 城市勾选
      cacheSelectArea: [], // 大区勾选
      cacheSelectStores: [] // 门店勾选
    };
  },
  // 监听属性 类似于data概念
  computed: {
    ...mapState('diclist',
      { 'areaMaps': state => state.areaMaps, // 大区缓存
        'cityMaps': state => state.cityMaps, // 城市缓存
        'storeMaps': state => state.storeMaps// 门店缓存
      })
  },
  // 监控data中的数据变化
  watch: {
    bigData: {
      immediate: true,
      handler(value) {
        value.regionList = value.regionList && value.regionList.map(x => ({ name: x.name, value: x.region })) || [];
        value.cityList = value.cityList && value.cityList.map(x => ({ name: x.name, value: x.city })) || [];
        value.storeList = value.storeList && value.storeList.map(x => ({ name: x.name, value: x.store })) || [];
        this.cacheSelectArea = value.regionList.slice(0);
        this.cacheSelectCitys = value.cityList.slice(0);
        this.cacheSelectStores = value.storeList.slice(0);
        const { id, parentId } = this.boxs;
        const arr = [value.regionList, value.cityList, value.storeList];
        if (arr.some(x => x.length > 0)) {
          this.$emit('collectData', {
            str: `${parentId}_${id}`,
            cityList: value.cityList,
            regionList: value.regionList,
            storeList: value.storeList
          });
        }
      }
    }

  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created () {},
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {},
  // 方法集合
  methods: {
    ...mapActions({ 'getData': 'diclist/getData' }),
    // 重置
    reset() {
      this.checkedCities = [];
      this.selectData = [];
    },
    // 确认
    sure() {
      const { id, parentId } = this.boxs;
      const data = this.selectData;
      this.dealData(data);
      switch (this.title) {
        case '添加大区':
          this.bigData.regionList = data;
          break;
        case '添加城市':
          this.bigData.cityList = data;
          break;
        case '添加门店':
          this.bigData.storeList = data;
          break;
      }
      this.visible = false;
      this.$emit('collectData', {
        str: `${parentId}_${id}`,
        cityList: this.bigData.cityList,
        regionList: this.bigData.regionList,
        storeList: this.bigData.storeList
      });
    },
    // 搜索
    search(value) {
      // console.log(value);
      if (!value) {
        this.dataReset();
        return;
      }
      const data = this.listData.filter(x => x.name.includes(value));
      this.listData = data;
    },
    // 数据恢复
    dataReset() {
      let ctr, str;
      const alen = this.cacheSelectArea.length; const clen = this.cacheSelectCitys.length;
      if (this.cacheSelectArea.length > 0) {
        ctr = this.cacheSelectArea.map(x => x.value).sort((a, b) => b - a).join('');
      }
      if (this.cacheSelectCitys.length > 0) {
        str = this.cacheSelectCitys.map(x => x.value).sort((a, b) => b - a).join('');
      }
      const stri = (!alen && !clen) ? 'all' : `${ctr || 0}_${str || 0}`;
      switch (this.title) {
        case '添加大区':
          this.listData = this.areaMaps.get('all');
          break;
        case '添加城市':
          this.listData = this.cityMaps.get(isNS(ctr) || 'all');
          break;
        case '添加门店':
          this.listData = this.storeMaps.get(stri);
          break;
      }
    },
    // 处理数据
    dealData(data) {
      switch (this.title) {
        case '添加大区':
          this.cacheSelectArea = data;
          break;
        case '添加城市':
          this.cacheSelectCitys = data;
          break;
        case '添加门店':
          this.cacheSelectStores = data;
          break;
      }
    },
    // 复选框勾选变化
    handleCheckedCitiesChange(value) {
      // console.log(value);
      if (value.length > 20) {
        this.msgError('最多可选20个');
        this.checkedCities = this.checkedCities.splice(0, 20);
        return;
      }
      const sData = this.selectData;
      let data;
      // 判断勾选与取消勾选
      if (value.length < sData.length) {
        this.selectData = sData.filter(x => value.includes(x.value));
      } else {
        const ids = value.slice(-1).pop();
        data = this.listData.filter(x => ids === x.value);
        this.selectData.push(...data);
      }
    },
    // 删除已选中的ATG
    clearTag(tag) {
      // todo
      const list = this.checkedCities;
      const selist = this.selectData;
      const data = selist.filter(x => x.value !== tag);
      this.selectData = data;
      this.checkedCities = list.filter(x => x !== tag);
      this.dealData(data);
    },
    // 添加tag
    addTag(params) {
      this.visible = true;
      this.searchVal = '';
      this.checkedCities = [];
      switch (params) {
        case 0:
          this.title = '添加大区';
          this.listData = this.areaMaps.get('all'); // 大区缓存
          this.selectData = this.cacheSelectArea.slice(0);
          this.checkedCities = this.selectData.map(x => x.value);
          break;
        case 1:
          this.title = '添加城市';
          this.getCityData(); // 城市缓存
          this.selectData = this.cacheSelectCitys.slice(0);
          this.checkedCities = this.selectData.map(x => x.value);
          break;
        case 2:
          this.title = '添加门店';
          this.getStoreData();
          this.selectData = this.cacheSelectStores.slice(0);
          this.checkedCities = this.selectData.map(x => x.value);
          break;
      }
    },
    // 获取联动门店的数据
    getStoreData() {
      const idA = this.cacheSelectArea.map(x => x.value);
      const idC = this.cacheSelectCitys.map(x => x.value);
      const ids = [...idA, ...idC];
      if (ids.length === 0) {
        this.listData = this.storeMaps.get('all'); // 门店缓存
      } else {
        const atr = idA.sort((a, b) => b - a).join('');
        const ctr = idC.sort((a, b) => b - a).join('');
        const str = `${atr || 0}_${ctr || 0}`;
        if (this.storeMaps.has(str)) {
          this.listData = this.storeMaps.get(str);
        } else {
          const params = {
            key: 'SET_STORE',
            str,
            param: {
              regions: idA,
              cities: idC
            }
          };
          this.getData(params).then(() => {
            this.listData = this.storeMaps.get(str);
          });
        }
      }
    },
    // 获取联动大区获取城市的数据
    getCityData() {
      if (this.cacheSelectArea.length === 0) {
        this.listData = this.cityMaps.get('all');
      } else {
        const ids = this.cacheSelectArea.map(x => x.value);
        const str = ids.sort((a, b) => b - a).join('');
        if (this.cityMaps.has(str)) {
          this.listData = this.cityMaps.get(str);
        } else {
          const params = {
            key: 'SET_CITY',
            str,
            param: {
              regions: ids
            }
          };
          this.getData(params).then(() => {
            this.listData = this.cityMaps.get(str);
          });
        }
      }
    },
    // remove tag
    handleClose(tag, index) {
    // todo
      // console.log(tag);
      let data;
      let sData;
      const cutData = this.checkedCities.filter(x => x !== tag);
      this.checkedCities = cutData;
      switch (index) {
        case 0:
          data = this.bigData.regionList.filter(x => x.value !== tag);
          this.bigData.regionList = data;
          sData = this.cacheSelectArea.filter(x => x.value !== tag);
          this.cacheSelectArea = sData;
          break;
        case 1:
          data = this.bigData.cityList.filter(x => x.value !== tag);
          this.bigData.cityList = data;
          sData = this.cacheSelectCitys.filter(x => x.value !== tag);
          this.cacheSelectCitys = sData;
          break;
        case 2:
          data = this.bigData.storeList.filter(x => x.value !== tag);
          this.bigData.storeList = data;
          sData = this.cacheSelectStores.filter(x => x.value !== tag);
          this.cacheSelectStores = sData;
          break;
      }
      const { id, parentId } = this.boxs;
      this.$emit('collectData', {
        str: `${parentId}_${id}`,
        cityList: this.bigData.cityList,
        regionList: this.bigData.regionList,
        storeList: this.bigData.storeList
      });
    }
  }
};
</script>
<style lang='scss' scoped>
.el-row {
    padding: 10px  5px;
    margin-bottom: 20px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
  }
  .el-tag + .el-tag {
    margin: 0 0 10px 10px;
  }
  .content{
    margin-top: 10px;
    padding: 5px 16px;
    // border-bottom: 1px solid #DCDFE6;
    .select-content{
      min-height: 38px;
      max-height: 106px;
      overflow-y: auto;
    }
    .select-cont{
      max-height: 230px;
      overflow-y: auto;
    }
    .divier{
      height: 1px;
      margin: 5px 0 10px;
      background:#DCDFE6;
    }
  }
</style>
